package com.et;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.UserManager;
import entites.WebUser;

//import dao.userexception.UnknownUserLoginException;



/**
 * Servlet implementation class Principale
 */
public class Principale extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
	private String messageAccueil = "Ceci est la page d'accueil !" ;
	// paramètres d'instance
	 private String urlErreurs = null;
	 @SuppressWarnings("rawtypes")
	private ArrayList erreursInitialisation = new ArrayList<String>();
	 private String[] parametres={"urlFormulaire","urlReponse","urlInscription",
			 "urlConnection","urlMessage","urlControleur","urlProfil", "urlServices", "urlContact", "urlAdmin","urlAjouterApp","urlUserList"};
	 @SuppressWarnings("rawtypes")
	private Map params=new HashMap<String,String>();
	private UserManager userManager = null ;
	
	/**
     * @see HttpServlet#HttpServlet()arg1
     */
    public Principale() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init() throws ServletException {
		// on récupère les paramètres d'initialisation de la servlet
		ServletConfig config = getServletConfig();
		 // on traite les autres paramètres d'initialisation		 		
	 
		//config.getServletContext().getContext(""); 
		
		 
		String valeur=null;
		 for(int i=0;i<parametres.length;i++){
		// valeur du paramètre
		 valeur=config.getInitParameter(parametres[i]);
		 // paramètre présent ?
		 if(valeur==null){
		 // on note l'erreur
		 erreursInitialisation.add("Le parametre ["+parametres[i]+"] n'a pas été initialisé");
		 }else{
		 // on mémorise la valeur du paramètre
		 params.put(parametres[i],valeur);
		 }
		 // l'url de la vue [erreurs] a un traitement particulier
		 urlErreurs = config.getInitParameter("urlError");
		 if (urlErreurs == null)
			 throw new ServletException("Le paramètre [urlErreurs] n'a pas été initialisé");		 
		 }
		 
		/* Context context = null;
			try {
				context = new InitialContext();
				userManager = (UserManager) context.lookup("UserManagerBean/remote-dao.UserManager") ;
				//Object obj = context.lookup("UserManagerBean/remote") ;
				//System.out.println(obj.getClass().getName());
			} catch (NamingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		if (erreursInitialisation.size() != 0) {
			// on passe la main à la page d'erreurs
			request.setAttribute("erreurs", erreursInitialisation);
			getServletContext().getRequestDispatcher(urlErreurs).forward(request, response);
			// fin
			return;
		}

		// on récupère la méthode d'envoi de la requête
		String methode=request.getMethod().toLowerCase();
		String action=request.getParameter("action");
		// action ?

		if(action==null){
			action="init";
		}
		// exécution action
		if(methode.equals("get") ) {
			if ( action.equals("init")){			
				doInit(request,response);
				return;
			}
			else if (action.equals("Inscription")){			 
				doInscription(request,response);
				return;
			}
			else if (action.equals("Connection")) {
				doConnection(request,response);
				return;
			}
			else if (action.equals("Contact")) {
				doContacter(request,response);
				return;
			}
			else if (action.equals("Profil")) {
				doEditProfil(request,response);
				return ;
			}
			else if (action.equals("Services")) {
				doServices(request,response);
				return ;
			}
			else if (action.equals("Disconnect")) {
				doLogout(request,response);
				return ;
			}
			else if (action.equals("ListUser")) {
				doList(request,response);
				return ;
			}
			else if (action.equals("AjouterApp")) {
				doAjouterAppli(request,response);
				return ;
			}
		}
		else if(methode.equals("post") ){
			if (action.equals("validFormulaire")) {
				doValidationFormulaire(request,response);
				return;
			}
			else if(action.equals("validInscription")){					 
				doValidationInscription(request,response);
				return ;
			}
		}
		// autres cas
		doInit(request,response);
	}

	private void doContacter(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		request.setAttribute("urlAction", (String)params.get("urlControleur"));
		getServletContext().getRequestDispatcher((String)params.get("urlContact")).forward(request, response);
		
	}

	private void doAjouterAppli(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		getServletContext().getRequestDispatcher((String)params.get("urlAjouterApp")).forward(request, response);
		return ;
	}

	private void doList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		getServletContext().getRequestDispatcher((String)params.get("urlUserList")).forward(request, response);
		return ;
		
		
	}

	private void doServices(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		getServletContext().getRequestDispatcher((String)params.get("urlServices")).forward(request, response);
		return ;
	}

	private void doLogout(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		HttpSession session = request.getSession(false) ;
		session.invalidate();
		
		doInit(request,response);
		return ;
		
	}

	private void doEditProfil(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession(false);
		if (!(( session != null ) && ( session.getAttribute("isLogged") != null))) {			
			doMessager(request, response, "Vous n'êtes pas loggé !") ;
			return ;
		}
		else {			
			request.setAttribute("urlAction", (String)params.get("urlControleur"));
			getServletContext().getRequestDispatcher((String)params.get("urlProfil")).forward(request,response);
			return ;
			
		}
			
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}
	
	protected void doInit (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		HttpSession session = request.getSession(false) ;
		
		if ( ( session != null ) && ( session.getAttribute("isLogged") != null ))  {
			request.setAttribute("message", messageAccueil ); 
			getServletContext().getRequestDispatcher((String)params.get("urlReponse")).forward(request, response);
			return ;			
		} 
		else 
		{			
			request.setAttribute("login", "" );
			request.setAttribute("password", "");		
			request.setAttribute("urlAction", (String)params.get("urlControleur"));
			
			getServletContext().getRequestDispatcher((String)params.get("urlFormulaire")).forward(request, response);
			return;
			
		}
			
	}
	
	protected void doInscription (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setAttribute("name", "");
		request.setAttribute("firstname", "");
		request.setAttribute("tel", "");
		request.setAttribute("email", "");
		request.setAttribute("email_sec", "");
		request.setAttribute("password", "");
		request.setAttribute("password_sec", "");
		
		request.setAttribute("urlAction", (String)params.get("urlControleur"));
		
		getServletContext().getRequestDispatcher((String)params.get("urlInscription")).forward(request, response);
		return;
	}

	protected void doConnection (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		
		
		request.setAttribute("login", "" );
		request.setAttribute("password", "");
		request.setAttribute("information","");
		
		request.setAttribute("urlAction", (String)params.get("urlControleur"));
		
		getServletContext().getRequestDispatcher((String)params.get("urlConnection")).forward(request, response);
		return;
	}
	
	protected void doValidationInscription (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		
		WebUser user = new WebUser();
	
		user.setAdmin(false);		
		user.setNom((String)request.getParameter("name"));
		user.setPrenom((String)request.getParameter("firstname"));
		user.setPassword((String)request.getParameter("password"));
		user.setPhone((String)request.getParameter("tel"));		
		user.setAdr_mail((String)request.getParameter("email"));
		
		String login = defineLogin ((String)request.getParameter("name"), (String)request.getParameter("firstname"));	
		user.setLogin(login);		
		
		//userManager.addUser(user);
		System.out.println("on ajoute un user");
		// Envoyer mail après inscription dans bdd ! 
		
		doMessager(request,response,"Votre inscription est terminée<br> Votre login est : "+login+" <br> Bon surf !");			
		return ;
	}
		
	private String defineLogin(String name, String firstname) {
		String login , suffix = "" ;
		Boolean b ;
		Integer compt = 0 ;
		
		do {
			b = true ;		
			login = "" ;
			try {
			login += firstname.charAt(0);
			login += name.substring(0, Math.min(7,name.length()));
			} catch ( NullPointerException e ) {
				System.out.println("Prenom ou Nom null");
			}
			login+= suffix;
			/*try {
				userManager.getUser(login);
			}catch ( UnknownUserLoginException e) {
				b = false ;
			}*/
			b = false;
			if ( b == true ) {
				if ( suffix =="")
					suffix = compt.toString() ;
				else 
					suffix = (compt++).toString() ;
			}
		}
		while ( b ) ;		

		return login ;	
	}
	
	protected void doValidationFormulaire (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 // on récupère les paramètres
		 String login = request.getParameter("login");
		 String password = request.getParameter("password");
	 
		 
		 WebUser user = new WebUser () ;
		 //user = userManager.getUser(login);
		 user.setLogin("jhermitt");
		 user.setPassword("password");
		 user.setNom("Hermitte");
		 user.setPrenom("Josselyn");
		 
		 WebUser user1 = new WebUser () ;
		 user1.setLogin("valent");
		 user1.setPassword("uiouiouio");
		 user1.setNom("Hermitte");
		 user1.setPrenom("Valentin");
		 user1.setAdmin(true);
		 
		 if ( user.getPassword().equals(password))
		 {			
		 HttpSession session = request.getSession();
		 	session.setAttribute("user", user);	
		 	session.setAttribute("name",user.getNom());		 
		 	session.setAttribute("password", password);
		 	session.setAttribute("isLogged", true);		 	
		 	request.setAttribute("message", "Identification completed !");
		 	
			 getServletContext().getRequestDispatcher((String)params.get("urlReponse")).forward(request, response);
			 return;
		 } 
		 else if ( user1.getPassword().equals(password))
		 {			
			 HttpSession session = request.getSession();
			 	session.setAttribute("user", user1);	
			 	session.setAttribute("name",user1.getNom());		 
			 	session.setAttribute("password", password);
			 	session.setAttribute("isLogged", true);		 	
			 	request.setAttribute("message", "Identification completed !<br>Interface administrateur : <br><a href='?action=AjouterApp'>Ajouter une application </a><br><a href='ListUser'>Lister les utilisateurs enregistrés</a>");
			 	
				 getServletContext().getRequestDispatcher((String)params.get("urlAdmin")).forward(request, response);
				 return;
			 }
		 
		 else {
			 
			 request.setAttribute("login", "");
			 request.setAttribute("password", "");
			 request.setAttribute("information", "Vos identifiants sont incorrects !") ;
			 
			 getServletContext().getRequestDispatcher((String)params.get("urlConnection")).forward(request, response);
			 return ;
		 }
			 
	}
	
	protected void doMessager (HttpServletRequest request, HttpServletResponse response, String message) throws ServletException, IOException {
		
		
			request.setAttribute("message", message);
			getServletContext().getRequestDispatcher((String)params.get("urlMessage")).forward(request, response);
			return ;
	}
		
}

